package com.sf.osms.dep.processor.handler.convert;

import java.text.ParseException;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sf.osms.dep.biz.ICommonServiceBiz;
import com.sf.osms.dep.domain.Agent;
import com.sf.osms.dep.domain.AgentConfig;
import com.sf.osms.dep.domain.Router;
import com.sf.osms.dep.processor.exception.ExceptionConstants;
import com.sf.osms.dep.processor.exception.RouterException;
import com.sf.osms.dep.processor.model.EventModel;
import com.sf.osms.dep.processor.util.CollectionUtil;
import com.sf.osms.dep.processor.util.DateUtil;
import com.sf.osms.dep.processor.util.ExceptionUtils;
import com.sf.osms.dep.processor.util.RouterConstants;

/**
 * 代理事件代码和顺丰事件的代码的转化
 * 
 * @author sfhq1405
 *
 */
public class EventCodeConverter implements Converter {

	private static Logger logger = LoggerFactory.getLogger(EventCodeConverter.class);
	private ICommonServiceBiz commonService;
	
	
	public ICommonServiceBiz getCommonService() {
		return commonService;
	}

	public void setCommonService(ICommonServiceBiz commonService) {
		this.commonService = commonService;
	}

	@SuppressWarnings("rawtypes")
	@Override
	public void convert(Router router, Map<String, String> routerFieldAndStr, Agent agentInfo, EventModel eventModel,
			ConverterChain chain) throws RouterException {
		// 转化eventCode和reasonCode
		String agentEventCode = router.getAgentEventCode();
		String agentReasonCode = router.getAgentReasonCode();
		String sfCode = null;
		if (!StringUtils.isEmpty(agentReasonCode)) {
			agentEventCode = agentEventCode + "," + agentReasonCode;
		}

		// 取出代理对应的sfCode的关系
		List<AgentConfig> agentCofigs = agentInfo.getAgentCofigs();
		// 如果未配置节点映射关系，则认为代理节点和顺丰节点映射相同不作关系转换
		if (CollectionUtil.isEmpty(agentCofigs)) {
			try {
				router.setEventCode(Integer.valueOf(router.getAgentEventCode()));
			} catch (Exception e) {
				logger.error("******代理：" + agentInfo.getName() + ",处理文件："
						+ eventModel.getFile().getAbsolutePath() + "," + "eventCode转化出现异常******" + e);
				router.addFailReasonList(ExceptionConstants.HANDLE_EVENT_CODE_ERROR_CODE);
				logger.error(ExceptionUtils.getExceptionStackString(e));
			}
			try {
				if (StringUtils.isNotEmpty(agentReasonCode)) {
					router.setReasonCode(Integer.valueOf(agentReasonCode));
				}
			} catch (Exception e) {
				logger.error("******代理：" + agentInfo.getName() + ",处理文件："
						+ eventModel.getFile().getAbsolutePath() + ","
						+ "reasonCode（失败原因节点节点）字段转化出现异常******");
				router.addFailReasonList(ExceptionConstants.HANDLE_RESON_CODE_ERROR_CODE);
				logger.error(ExceptionUtils.getExceptionStackString(e));
			}
			
		} else {
			
			if(agentCofigs.get(0).getConfigType() == 1){
				for (AgentConfig agentConfig : agentCofigs) {
					// agentCode与sfCode对应的默认类型为1 简单映射
					if (agentConfig.getAgentCode().equalsIgnoreCase(agentEventCode) && 1 == agentConfig.getConfigType()) {
						sfCode = agentConfig.getSfCode();
						break;
					}
				}
				
				//条件表达式的映射
				/*try {
					sfCode = getDynamicSfCode(agentInfo, router);
				} catch (Exception e1) {
					logger.error("******代理：" + agentInfo.getName() + ",处理文件："
							+ eventModel.getFile().getAbsolutePath() + "," + "eventCode条件表达式转化出现异常******" + e1);
					router.setFailReasonList(ExceptionConstants.HANDLE_EVENT_CODE_ERROR_CODE);
					sfCode = "condition";
				}*/
				
				if (StringUtils.isEmpty(sfCode)) {
					
					// 如果未配置节点映射关系，则认为代理节点和顺丰节点映射相同不作关系转换
					try {
						router.setEventCode(Integer.valueOf(router.getAgentEventCode()));
					} catch (Exception e) {
						logger.error("******代理：" + agentInfo.getName() + ",处理文件："
								+ eventModel.getFile().getAbsolutePath() + "," + "eventCode转化出现异常******" + e);
						router.addFailReasonList(ExceptionConstants.HANDLE_EVENT_CODE_ERROR_CODE);
						logger.error(ExceptionUtils.getExceptionStackString(e));
					}
					try {
						if (StringUtils.isNotEmpty(agentReasonCode)) {
							router.setReasonCode(Integer.valueOf(agentReasonCode));
						}
					} catch (Exception e) {
						logger.error("******代理：" + agentInfo.getName() + ",处理文件："
								+ eventModel.getFile().getAbsolutePath() + ","
								+ "reasonCode（失败原因节点节点）字段转化出现异常******");
						router.addFailReasonList(ExceptionConstants.HANDLE_RESON_CODE_ERROR_CODE);
						logger.error(ExceptionUtils.getExceptionStackString(e));
					}
					
					
				}else{
					String[] sfCodes = sfCode.split(",");
					Integer eventCode = null;
					for (int i = 0; i < sfCodes.length; i++) {
						if (i == 0) {
							try {
								eventCode = Integer.valueOf(sfCodes[i].trim());
								router.setEventCode(eventCode);
							} catch (Exception e) {
								logger.error("******代理：" + agentInfo.getName() + ",处理文件："
										+ eventModel.getFile().getAbsolutePath() + "," + "eventCode转化出现异常******" + e);
								router.addFailReasonList(ExceptionConstants.HANDLE_EVENT_CODE_ERROR_CODE);
								logger.error(ExceptionUtils.getExceptionStackString(e));
							}

						}
						if (i == 1) {
							try {
								Integer resonCode = Integer.valueOf(sfCodes[i].trim());
								router.setReasonCode(resonCode);
								
							} catch (Exception e) {
								logger.error("******代理：" + agentInfo.getName() + ",处理文件："
										+ eventModel.getFile().getAbsolutePath() + ","
										+ "reasonCode（失败原因节点节点）字段转化出现异常******");
								router.addFailReasonList(ExceptionConstants.HANDLE_RESON_CODE_ERROR_CODE);
								logger.error(ExceptionUtils.getExceptionStackString(e));
							}
						}
					}
				}
			}
			
		}
		
		//对80节点的处理
		if(null != router.getEventCode() && 80 == router.getEventCode()){
			router.setSignTypeCode("0");
			if(StringUtils.isNotBlank(agentInfo.getPodFlag()) && "1".equals(agentInfo.getPodFlag().trim())){
				router.setPodSendCount(0); 
				router.setPodStatus(RouterConstants.POD_START_STATUS); //0为80节点的开始状态
				
			}		
		}
		
		//对44节点处理
		if(null != router.getEventCode() && 44 == router.getEventCode() && StringUtils.isNotEmpty(router.getAgentWaybill())){
			router.setExtendAttach3(router.getAgentWaybill());
		}
		
		// 进行fvp把枪时间的转换
		/**
		 
			Date oldBarDate = router.getBarDate();
			String date = DateUtil.dateFomat(oldBarDate, "yyyy-MM-dd");
			Date oldBarTime = router.getBarTime();
			String time = DateUtil.dateFomat(oldBarTime, "HH:mm:ss");
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-ddHH:mm:ss");
			try {
				router.setFvpBarScanTm(sdf.parse(date + time));
			} catch (Exception e) {
				logger.error("****转换fvpbartime时间有误******");
				throw new RouterException(ExceptionConstants.HANDLE_LOGIC_ERROR_CODE, ExceptionConstants.TIME_EMPTY);
			}
		* 
		 */
		
		//进行时区的转换
		if(null != router.getBarDate() && null != router.getBarTime() && null != agentInfo.getTimeZoneTranfer()){
			Calendar dateTransfer = Calendar.getInstance();
			try {
				dateTransfer.setTime(DateUtil.formatDate(DateUtil.dateFomat(router.getBarDate(), "yyyy-MM-dd")+
									 DateUtil.dateFomat(router.getBarTime(), "HH:mm:ss")));
			} catch (ParseException e) {
				
				logger.error("******代理：" + agentInfo.getName() + ",处理文件："
						+ eventModel.getFile().getAbsolutePath() + ","
						+ "时区转换出现异常******");
				logger.error(ExceptionUtils.getExceptionStackString(e));
				router.addFailReasonList(ExceptionConstants.HANDLE_TIME_ZONE_ERROR_CODE);
			}
			dateTransfer.add(Calendar.HOUR_OF_DAY, agentInfo.getTimeZoneTranfer());
			router.setBarDate(dateTransfer.getTime());
			router.setBarTime(dateTransfer.getTime());
		}
		chain.convert(router, routerFieldAndStr, agentInfo, eventModel, chain);

	}	

}
